#!/bin/bash
# optimize_server.sh

echo "=== Optimizing system for high-concurrency HTTP server ==="

# 1. 增加文件描述符限制
echo "Setting file descriptor limits..."
ulimit -n 100000

# 2. 优化TCP参数
echo "Optimizing TCP parameters..."

# 减少TIME_WAIT状态持续时间
echo 10 > /proc/sys/net/ipv4/tcp_fin_timeout

# 允许重用TIME_WAIT套接字
echo 1 > /proc/sys/net/ipv4/tcp_tw_reuse

# 增加连接队列大小
echo 65536 > /proc/sys/net/core/somaxconn
echo 65536 > /proc/sys/net/ipv4/tcp_max_syn_backlog

# 快速回收TIME_WAIT连接（谨慎使用）
echo 1 > /proc/sys/net/ipv4/tcp_tw_recycle 2>/dev/null || echo "tcp_tw_recycle not available"

# 增加本地端口范围
echo "1024 65535" > /proc/sys/net/ipv4/ip_local_port_range

# 减少SYN重试次数
echo 2 > /proc/sys/net/ipv4/tcp_syn_retries
echo 2 > /proc/sys/net/ipv4/tcp_synack_retries

# 3. 显示当前配置
echo "=== Current TCP settings ==="
echo "tcp_fin_timeout: $(cat /proc/sys/net/ipv4/tcp_fin_timeout)"
echo "tcp_tw_reuse: $(cat /proc/sys/net/ipv4/tcp_tw_reuse)"
echo "somaxconn: $(cat /proc/sys/net/core/somaxconn)"
echo "tcp_max_syn_backlog: $(cat /proc/sys/net/ipv4/tcp_max_syn_backlog)"
echo "ip_local_port_range: $(cat /proc/sys/net/ipv4/ip_local_port_range)"

echo "System optimization completed!"